package com.lsh.service.impl;

import com.lsh.service.RabbitService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * @author ：LiuShihao
 * @date ：Created in 2021/3/19 2:59 下午
 * @desc ：
 */
@Service
public class RabbitServiceImpl implements RabbitService {
    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RedisTemplate redisTemplate;


    @Autowired
    ConfirmCallbackServiceImpl confirmCallbackService;

    @Autowired
    ReturnCallbackServiceImpl returnCallbackService;

    @PostConstruct
    public void init() {
        RedisSerializer redisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(redisSerializer);
        redisTemplate.setValueSerializer(redisSerializer);
        redisTemplate.setHashKeySerializer(redisSerializer);
        redisTemplate.setHashValueSerializer(redisSerializer);
    }

    /**
     * Redis 中金额减100
     * 发送消息到MQ
     * @return
     */
    @Override
    public String Consumer(){
        try {
            redisTemplate.opsForValue().decrement("money",100L);
            String money = (String) redisTemplate.opsForValue().get("money");
            System.out.println("==============================");
            System.out.println("扣减100元，消费成功~"+"当前余额："+money+" 元 ");
            System.out.println("发送mq...");

            /**
             * 确保消息发送失败后可以重新返回到队列中
             * 注意：yml需要配置 publisher-returns: true
             */
            rabbitTemplate.setMandatory(true);

            /**
             * 消费者确认收到消息后，手动ack回执回调处理
             */
            rabbitTemplate.setConfirmCallback(confirmCallbackService);

            /**
             * 消息投递到队列失败回调处理
             */
            rabbitTemplate.setReturnCallback(returnCallbackService);

            //将消息投递到不存在的交换机
            //rabbitTemplate.convertAndSend("queue1", Instant.now().toString());
            //将消息投递到存在的交换机
            rabbitTemplate.convertAndSend("queue", "consumer端金额扣减成功");


        }catch (Exception e){
            throw new RuntimeException("发生异常");
        }
        return "金额扣减成功并且发送mq！";

    }
}
